package com.example.cyk.controller;

import com.example.cyk.config.response.AppReturn;
import com.example.cyk.config.response.CodeMsg;
import com.example.cyk.model.vo.ArticleVO;
import com.example.cyk.service.IArticleService;
import com.sun.org.apache.bcel.internal.classfile.Code;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @GetMapping("/boards")
    public AppReturn boards() {
        List<String> allBoard = articleService.getAllBoard();
        return AppReturn.success(allBoard);
    }

    @GetMapping("/articles_board")
    public AppReturn articlesBoard(@NonNull String board, @NonNull Integer curPage,
                                   @NonNull Integer pageSize) {
        //1.非法校验
        if(curPage <= 0 || pageSize <= 0) {
            return AppReturn.fail(CodeMsg.FAIL_ERROR_CURPAGE_PAGESIZE);
        }
        List<ArticleVO> articleList = articleService.getArticleList(board, curPage, pageSize);
        return AppReturn.success(articleList);
    }

    @GetMapping("/total_board")
    public AppReturn totalBoard(@NonNull String board) {
        Integer total = articleService.getTotal(board);
        return AppReturn.success(total);
    }

    @PostMapping("/publish")
    public AppReturn publish(@RequestBody @NonNull ArticleVO articleVO) {
        //1.非空校验
        if(!StringUtils.hasLength(articleVO.getTitle()) ||
                !StringUtils.hasLength(articleVO.getDesc()) ||
        !StringUtils.hasLength(articleVO.getContent()) ||
        !StringUtils.hasLength(articleVO.getBoard())) {
            log.warn(CodeMsg.FAIL_NULL_ARTICLE.toString());
            return AppReturn.fail(CodeMsg.FAIL_NULL_ARTICLE);
        }
        //2.添加文章
        articleService.addArticle(articleVO);
        log.info("用户发布文章！ userId: " + articleVO.getUserId() + ", title: "
                + articleVO.getTitle());
        return AppReturn.success();
    }


}
